package yunhe.control;



import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;

import yunhe.entity.Food;
import yunhe.entity.Ground;
import yunhe.entity.Snake;
import yunhe.listener.SnakeListener;
import yunhe.util.Global;
import yunhe.view.GamePanel;
/**
 * 控制器类  
 * 用控制器来控制Snake,Food,Ground,GamePanel这四个对象
 * 继承KeyAdapter方法来监听键盘事件(蛇移动的方向变化)
 * 实现snakeListener接口
 * @author 六六大欢
 *
 */
public class Controlller extends KeyAdapter implements SnakeListener{
	private Snake snake;
	private Food food;
	private Ground ground;
	private GamePanel gamePanel;
	/**
	 * 构造函数初始化
	 * @param snake
	 * @param food
	 * @param ground
	 * @param gamePanel
	 */
	public Controlller(Snake snake, Food food, Ground ground, GamePanel gamePanel) {
		super();
		this.snake = snake;
		this.food = food;
		this.ground = ground;
		this.gamePanel = gamePanel;
	}
	/**
	 * 重现keyPressed方法
	 */
	@Override
	public void keyPressed(KeyEvent e) {
		int keycode=e.getKeyCode();
		switch (keycode) {
		case KeyEvent.VK_UP:
			snake.changeDirection(Snake.UP);
			break;
		case KeyEvent.VK_DOWN:
			snake.changeDirection(Snake.DOWN);
			break;
		case KeyEvent.VK_LEFT:
			snake.changeDirection(Snake.LEFT);
			break;
		case KeyEvent.VK_RIGHT:
			snake.changeDirection(Snake.RIGHT);
			break;
		}
	}
	/**
	 * 重现snakeMoved方法
	 */
	@Override
	public void snakeMoved(Snake snake) {
		System.out.println("判断移动的时候是否碰到自己,食物,障碍物");
		//显示食物,身体,障碍物
		if(food.isEatBySnake(snake)){
			snake.eatFood(food);
			//食物被吃了之后,位置重设
			food.addFood(getPoint());
		}
		gamePanel.display(snake, food, ground);
		
	}
	/**
	 * 游戏开始
	 */
	public void startGame(){
		snake.start();
		food.addFood(getPoint());
		
	}
	/**
	 * 设置食物点的位置
	 * @return
	 */
	public Point getPoint() {
		int x=new Random().nextInt(Global.WIDTH);
		int y=new Random().nextInt(Global.HEIGHT);
		return new Point(x, y);
	}
	
	
} 
